package xyz.lwm.lazycat.utility.scan;

import xyz.lwm.lazycat.utility.StringUtil;
import xyz.lwm.lazycat.utility.resource.Resource;

import java.util.function.Predicate;

import static xyz.lwm.lazycat.utility.scan.PathRegex.REG_SLASH_END;
import static xyz.lwm.lazycat.utility.scan.Scanner.SLASH;

/**
 * 资源路径匹配器
 *
 * @author lwm
 */
public class ResourceMatcher implements Predicate<Resource> {

    // 正则表达式, 用于匹配文件路径
    private final PathRegex regex;

    public ResourceMatcher(LocationPattern locationPattern) {
        this.regex = PathRegex.toRegex(locationPattern.getPattern());
    }

    @Override
    public boolean test(Resource resource) {
        String path = getPathIfScannedClasspath(resource);
        return regex.matches(path);
    }

    // 获取文件的类路径路径, 如果是类路径, 则需要去掉类路径前缀, 否则无法匹配
    protected String getPathIfScannedClasspath(Resource resource) {
        String filePath = resource.getPath();
        filePath = filePath.replaceAll("\\\\+", String.valueOf(SLASH));

        if (StringUtil.isNotBlank(resource.getClasspath())) {
            filePath = resource.getClasspath();
        }

        if (resource.isDir()) {
            boolean regSlash = regex.toString().endsWith(REG_SLASH_END);
            boolean pathSlash = filePath.endsWith(String.valueOf(SLASH));
            if (regSlash && !pathSlash) {
                filePath = filePath + SLASH;
            } else if (!regSlash && pathSlash) {
                filePath = filePath.substring(0, filePath.length() - 1);
            }
        }

        return filePath;
    }

    @Override
    public String toString() {
        return "PathMatcher{" +
                "regex='" + regex + '\'' +
                '}';
    }

}
